<template>
  <div class="app">
    <!-- 图片上传的两种方式
      1.表单上传：缺点：上传时会刷新 页面跳转
      2.ajax上传：
        2.1 原生ajax上传
    2.2 element-ui上传-->

    <!-- 表单上传 -->
    <!-- multipart/form-data:  适用于使用<input> 标签上传文件,二进制提 -->
    <!-- <form :action="serveHost+'/admin/xy/upload/uploadImg'" method="post" enctype="multipart/form-data">
         name属性用于标识当前内容在哪个字段保存，对于file类型，后台一般接收key为'file'的字段
          <input type="file" name="file">
          <button type="submit">上传</button>
    </form>-->

    <!-- ajax上传 -->
    <!-- <input type="file" @change="upload($event)" />
    <div class="imglist">
          <img :src="tempImg" alt="" style="width:100px;height:100px">
    </div>-->

    <!-- element-ui上传 -->
    <!-- <el-upload
      class="upload-demo"
      :action="serveHost +'/admin/xy/upload/uploadImg'"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :file-list="fileList"
      list-type="picture"
    >-->
    <!-- <el-button size="small" type="primary">点击上传</el-button> -->
    <input type="file" @change="upload($event)" />
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    <ul>
      <li v-for="item in fileList" :key="item.id">
        <img :src="serveHost + '/' + item.dir + '/' + item.fileName" alt @click="preview(item)" />
        <div class="title">{{item.title}}</div>
        <button @click="del(item)">删除</button>
      </li>
    </ul>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRow"
      ></el-pagination>
    </div>
    <div class="mask" v-show="flag">
      <div class="preview">
        <img :src="tempSrc" alt @click="close" />
        <input type="text" :value="title" @change="updateTitle($event)" />
      </div>
    </div>
  </div>
</template>

<script>
import { updateTitle, list, delItem } from "@/api/material/img";
import settingsFile from "@/settings";
import axios from "axios";
import qs from "qs";
// var url = settingsFile.host + "/admin/xy/upload/list";
export default {
  components: {},
  data() {
    return {
      flag: false,
      title: "",
      tempSrc: "",
      serveHost: settingsFile.host,
      file: {},
      fileList: [],
      totalPage: 0,
      totalRow: 0,
      currentPage: 1,
      pageSize: 10
    };
  },
  computed: {},
  created() {
    this.getList();
  },
  mounted() {},
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      console.log(this.currentPage);
      this.getList();
    },
    getList() {
      var url = this.serveHost + "/admin/xy/upload/list";

      // axios请求未封装，所以参数需要序列化，尽量使用封装好的请求(已对参数进行序列化)
      axios
        .post(
          url,
          qs.stringify({
            start: this.currentPage,
            limit: this.pageSize
          })
        )
        .then(res => {
          this.fileList = res.data.data.list;
          this.totalPage = res.data.data.totalPage;
          this.totalRow = res.data.data.totalRow;
          console.log(res);
        });
    },
    preview(item) {
      this.flag = true;
      // console.log(item);
      this.tempSrc = this.serveHost + "/" + item.dir + "/" + item.fileName;
      this.title = item.title;
      this.file = item;
      // this.title = file.name;
      // this.tempSrc = this.serveHost + "/" + file.response.url;
    },
    updateTitle(e) {
      console.log(e);
      // var updUrl = this.serveHost + "/admin/xy/upload/updateTitle";
      updateTitle({
        title: e.target.value,
        id: this.file.id
      }).then(res => {
        // console.log(res);
        this.title = e.target.value;
        var i = this.fileList.findIndex(el => el.id == this.file.id);
        this.fileList[i].title = e.target.value;
        this.flag = false;
      });
    },
    close() {
      this.flag = false;
    },
    del(item) {
      this.$confirm("您确定要删除当前项吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delItem({
          id: item.id
        }).then(res => {
          console.log(res);
          var i = this.fileList.findIndex(el => el.id == item.id);
          this.fileList.splice(i, 1);
          this.getList();
        });
      });
    },

    upload(e) {
      // console.log(e);
      // 通过$event 事件对象获取目标元素 bom
      var inputEl = e.target;
      var value = e.target.value;
      var arr = value.split("\\"); //String.split()方法无法识别转义字符'\' 要使用 \\ 解决
      this.title = arr[2];
      // 获取上传的资源文件
      var file = inputEl.files[0];
      // FormData是window的原生对象，代表表单对象
      var fd = new FormData();
      // new一个表单对象，用append给其追加一个属性
      fd.append("file", file);
      var url = this.serveHost + "/admin/xy/upload/uploadImg";
      axios.post(url, fd).then(res => {
        // console.log(res);
        this.tempSrc = this.serveHost + "/" + res.data.url;
        var obj = {
          title: this.title,
          tempSrc: this.tempSrc,
          id: res.data.id
        };
        this.fileList.push(obj);
      });
    }
  }
};
</script>

<style scoped lang="scss">
.app {
  position: relative;
  height: 700px;
  ul {
    width: 100%;
    height: 320px;
    padding: 20px;
    box-sizing: border-box;
    li {
      float: left;
      width: 120px;
      height: 120px;
      margin: 10px;
      list-style: none;

      img {
        width: 100%;
        height: 80px;
      }
      .title {
        width: 100%;
        height: 20px;
        line-height: 20px;
        text-align: center;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      button {
        margin-left: 30px;
        width: 50px;
        height: 20px;
        font-size: 12px;
      }
    }
  }
  .upload-demo {
    padding: 20px;
    box-sizing: border-box;
    width: 20%;
  }
  .mask {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, 37%);
    width: 200px;
    height: 200px;
    .preview {
      width: 100%;
      height: 100%;
      img {
        width: 100%;
        height: 86%;
      }
      input {
        width: 100%;
      }
    }
  }
}
</style>
